<template>
  <a-layout style="padding: 10px">
    <a-layout-content
      :style="{ background: '#fff', padding: '10px', margin: 0, minHeight: '280px' }"
    >
      <a-space direction="vertical" style="width: 100%">
        <a-button type="primary" @click="showCreateDrawer">
          <template #icon><PlusOutlined /></template>
          创建新分类
        </a-button>
        <a-breadcrumb separator="/">
          <a-breadcrumb-separator>/</a-breadcrumb-separator>
          <template v-for="categoryName in categoryPathBreadcrumb" :key="categoryName">
            <a-breadcrumb-item href="">
              <span>{{ categoryName }}</span>
            </a-breadcrumb-item>
          </template>
        </a-breadcrumb>
        <a-table :data-source="categoriesRef" :columns="categoryColumns" :pagination="false">
          <template #headerCell="{ column }">
            <template v-if="column.key === 'name'">
              <span style="color: #1890ff">Name</span>
            </template>
          </template>
          <template
            #customFilterDropdown="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }"
          >
            <div style="padding: 8px">
              <a-input
                ref="searchInput"
                :placeholder="`Search ${column.dataIndex}`"
                :value="selectedKeys[0]"
                style="display: block; width: 188px; margin-bottom: 8px"
                @change="(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])"
                @press-enter="
                  handleCategoriesDownOptionSearchFunc(selectedKeys, confirm, column.dataIndex)
                "
              />
              <a-button
                type="primary"
                size="small"
                style="width: 90px; margin-right: 8px"
                @click="
                  handleCategoriesDownOptionSearchFunc(selectedKeys, confirm, column.dataIndex)
                "
              >
                <template #icon><SearchOutlined /></template>
                Search
              </a-button>
              <a-button
                size="small"
                style="width: 90px"
                @click="handleCreateCategoryFormReset(clearFilters)"
              >
                Reset
              </a-button>
            </div>
          </template>
          <template #customFilterIcon="{ filtered }">
            <search-outlined :style="{ color: filtered ? '#108ee9' : undefined }" />
          </template>
          <template #bodyCell="{ text, column, record }">
            <!-- 定义 avatar 插槽 -->
            <template v-if="column.dataIndex === 'categoryImageUrl'">
              <a-image
                :src="record.categoryImageUrl"
                fallback=""
              />
            </template>
            <span v-if="state.searchText && state.searchedColumn === column.dataIndex">
              <template
                v-for="(fragment, i) in text
                  .toString()
                  .split(new RegExp(`(?<=${state.searchText})|(?=${state.searchText})`, 'i'))"
              >
                <mark
                  v-if="fragment.toLowerCase() === state.searchText.toLowerCase()"
                  :key="i"
                  class="highlight"
                >
                  {{ fragment }}
                </mark>
                <template v-else>{{ fragment }}</template>
              </template>
            </span>
            <template v-else-if="column.dataIndex === 'operation'">
              <a-space>
                <a-popconfirm
                  title="Sure to next?"
                  v-if="record.categoryParentId"
                  @confirm="
                    populateCategoryData(
                      {
                        page: {
                          current: 1,
                          pageSize: pagination.pageSize,
                        },
                        level: record.level - 1,
                      },
                      false,
                      record.path,
                      record.categoryName,
                    )
                  "
                >
                  <a-button type="primary" shape="circle" :icon="h(ArrowLeftOutlined)" />
                </a-popconfirm>
                <a-popconfirm
                  title="Sure to next?"
                  v-if="record.isParent"
                  @confirm="
                    populateCategoryData(
                      {
                        page: {
                          current: 1,
                          pageSize: pagination.pageSize,
                        },
                        level: record.level + 1,
                      },
                      true,
                      record.path,
                      record.categoryName,
                    )
                  "
                >
                  <a-button type="primary" shape="circle" :icon="h(ArrowRightOutlined)" />
                </a-popconfirm>
                <a-button
                  type="primary"
                  shape="circle"
                  :icon="h(FormOutlined)"
                  @click="showEditDrawer(toRaw(record))"
                />
              </a-space>
            </template>
          </template>
        </a-table>
        <a-row justify="end">
          <a-col :span="8" style="text-align: end">
            <a-pagination
              v-model:current="pagination.current"
              :total="pagination.total"
              :page-size="pagination.pageSize"
              @change="handleTablePageChangeFunc"
              :show-total="(total: number) => `共 ${total} 条`"
            />
          </a-col>
        </a-row>
      </a-space>
      <a-drawer
        :title="drawModRef === 'create' ? '创建新分类' : '编辑新分类'"
        width="50%"
        :open="openDrawRef"
        @close="onClose"
        :autofocus="true"
      >
        <a-form
          ref="createCategoryFormRef"
          :model="createCategoryFormModel"
          :rules="createCategoryRules"
          layout="horizontal"
          :label-col="{ span: 3 }"
          label-align="right"
        >
          <a-row :span="24">
            <a-col :span="24" style="text-align: left">
              <a-form-item label="分类名称" name="categoryName">
                <a-input
                  v-model:value="createCategoryFormModel.categoryName"
                  placeholder="请输入分类名称"
                />
              </a-form-item>
              {{ createCategoryFormModel }}
              <a-form-item label="父分类名称" name="categoryParentId">
                <CategorySelect
                  v-if="drawModRef === 'create'"
                  @category:selected="
                    (categoryId) => (createCategoryFormModel.categoryParentId = categoryId)
                  "
                />
                <a-tag v-else-if="createCategoryFormModel.categoryParentId">{{
                  createCategoryFormModel.categoryParentId
                }}</a-tag>
              </a-form-item>
              <a-form-item label="数量单位" name="unit">
                <a-input
                  v-model:value="createCategoryFormModel.unit"
                  placeholder="请输入数量单位"
                />
              </a-form-item>
              <a-form-item label="排序" name="sort">
                <a-input-number
                  v-model:value="createCategoryFormModel.sort"
                  placeholder="请输入排序"
                />
              </a-form-item>
              <a-form-item label="是否展示" name="isDisplay">
                <a-checkbox v-model:checked="createCategoryFormModel.isDisplay"
                  >是否展示</a-checkbox
                >
              </a-form-item>
              <a-form-item label="分类图片" name="categoryImageUrl">
                <a-upload
                  v-model:file-list="createCategoryFormModel.categoryImageUrls"
                  list-type="picture-card"
                  :max-count="1"
                  action="http://127.0.0.1:20020/file-server/file/upload?bucket=bosi-mall-app-web&path=category,image"
                >
                  <div>
                    <plus-outlined />
                    <div style="margin-top: 8px">Upload</div>
                  </div>
                </a-upload>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="24" style="text-align: right">
              <a-space-compact>
                <a-button type="primary" @click="onClose">取消</a-button>
                <a-button type="primary" @click="onSummitFunc">提交</a-button>
              </a-space-compact>
            </a-col>
          </a-row>
        </a-form>
      </a-drawer>
    </a-layout-content>
  </a-layout>
</template>

<script lang="ts" setup>
  import { h, reactive, ref, toRaw } from 'vue';
  import { Rule } from '@/components/Form';
  import {
    ArrowLeftOutlined,
    ArrowRightOutlined,
    FormOutlined,
    PlusOutlined,
    SearchOutlined,
  } from '@ant-design/icons-vue';
  import {
    CategoryItem,
    CategorySearchPage,
    CreateCategory,
  } from '#/goods-manage/category-manage/category';
  import {
    categories,
    categoriesCount,
    createCategory,
    updateCategory,
  } from '@/api/goods-manage/category-manage/category';
  import { DialogMod } from '#/global';
  import CategorySelect from '@/my-components/CategorySelect.vue';
  import { UploadFile } from 'ant-design-vue/es/upload/interface';

  const categoryPathBreadcrumb: string[] = [];
  const categoryPathBreadcrumbRef = ref(categoryPathBreadcrumb);
  // 默认分页配置
  const pagination = {
    total: 0,
    current: 1,
    pageSize: 10,
  };
  const paginationRef = reactive(pagination);

  const currentLevel = 0;

  const currentLevelRef = ref<number>(currentLevel);
  // 创建新分类
  const onSummitFunc = async () => {
    try {
      const values = toRaw(await createCategoryFormRef.value.validateFields()) as CreateCategory;
      if (
        createCategoryFormModel.categoryImageUrls &&
        createCategoryFormModel.categoryImageUrls.length > 0
      ) {
        values.categoryImageUrl = createCategoryFormModel.categoryImageUrls[0].response;
      }

      if (drawModRef.value === 'create') {
        await createCategory(values);
      } else {
        await updateCategory(createCategoryFormModel.id as string, values);
      }
      onClose();
      await populateCategoryData(pageQueryCategories);
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  };

  const createCategoryFormRef = ref();

  type categoryForm = {
    id: string | null;
    categoryName: string | null;
    categoryParentId?: string | null;
    unit: string;
    sort: number;
    isDisplay: boolean;
    categoryImageUrls?: UploadFile[];
  };

  const createCategoryFormModel = reactive<categoryForm>({
    id: null,
    categoryName: null,
    categoryParentId: null,
    unit: '件',
    sort: 0,
    isDisplay: true,
    categoryImageUrls: [],
  });

  const createCategoryRules: Record<string, Rule[]> = {
    categoryName: [{ required: true, message: '请输入分类名称', max: 255 }],
    unit: [{ required: true, message: '请输入单位', max: 16 }],
    sort: [{ required: false, message: '请输入排序' }],
  };

  const openDrawRef = ref<boolean>(false);
  const drawModRef = ref<DialogMod>('create');

  const showDrawer = (mode: DialogMod) => {
    openDrawRef.value = true;
    drawModRef.value = mode;
  };

  // 展示创建抽屉
  const showCreateDrawer = () => {
    showDrawer('create');
  };

  // 展示编辑抽屉
  const showEditDrawer = (record: CategoryItem) => {
    createCategoryFormModel.id = record.id;
    createCategoryFormModel.categoryName = record.categoryName;
    createCategoryFormModel.sort = record.sort;
    createCategoryFormModel.unit = record.unit;
    createCategoryFormModel.isDisplay = record.isDisplay;
    if (record.categoryImageUrl) {
      createCategoryFormModel.categoryImageUrls = [
        {
          uid: '',
          name: '',
          percent: 0,
          response: record.categoryImageUrl,
          url: record.categoryImageUrl,
        },
      ];
    }
    showDrawer('edit');
  };

  const onClose = () => {
    openDrawRef.value = false;
  };

  const categoriesRef = ref<CategoryItem[]>([]);

  const populateCategoryData = async (
    pageParam: CategorySearchPage,
    next?: boolean,
    path?: string,
    categoryName?: string,
  ) => {
    if (categoryName && path) {
      let paths: string[] = [];
      categoryPathBreadcrumbRef.value.length = 0;
      let split = path.split('/').filter((part) => part.trim() !== '');
      if (next) {
        paths.push(...split);
      } else {
        split.pop();
        split.pop();
        paths.push(...split);
      }
      categoryPathBreadcrumbRef.value.push(...paths);
    }
    const { level } = pageParam;
    paginationRef.total = await categoriesCount({ level: level });
    paginationRef.current = pageParam.page.current;
    paginationRef.pageSize = pageParam.page.pageSize;
    if (paginationRef.total <= 0) {
      return;
    }
    const categoryItems = await categories(pageParam);
    const items: CategoryItem[] = [];
    items.push(...categoryItems);
    categoriesRef.value = items;
    currentLevelRef.value = level as number;
  };
  const pageQueryCategories: CategorySearchPage = {
    page: {
      current: pagination.current,
      pageSize: pagination.pageSize,
    },
    level: currentLevelRef.value,
  };
  // 查询分类列表
  populateCategoryData(pageQueryCategories);

  const handleTablePageChangeFunc = (current: number, pageSize: number) => {
    populateCategoryData({
      page: { current: current, pageSize: pageSize },
      level: currentLevelRef.value,
    });
  };

  const state = reactive({
    searchText: '',
    searchedColumn: '',
  });

  const searchInput = ref();
  // 分类列表-表头
  const categoryColumns = [
    {
      title: '分类名称',
      dataIndex: 'categoryName',
      key: 'categoryName',
      customFilterDropdown: true,
    },
    {
      title: '分类图片',
      dataIndex: 'categoryImageUrl',
      key: 'categoryImageUrl',
      width: '25%',
    },
    {
      title: '层级',
      dataIndex: 'level',
      key: 'level',
    },
    {
      title: '排序',
      dataIndex: 'sort',
      key: 'sort',
    },
    {
      title: '单位',
      dataIndex: 'unit',
      key: 'unit',
    },
    {
      title: '路径',
      dataIndex: 'path',
      key: 'path',
    },
    {
      title: 'operation',
      dataIndex: 'operation',
    },
  ];

  const handleCategoriesDownOptionSearchFunc = (
    selectedKeys: string[],
    confirm: Function,
    dataIndex: string,
  ) => {
    confirm();
    state.searchText = selectedKeys[0];
    state.searchedColumn = dataIndex;

    const pageQueryCategories: CategorySearchPage = {
      page: {
        current: pagination.current,
        pageSize: pagination.pageSize,
      },
      categoryName: state.searchText,
    };
    populateCategoryData(pageQueryCategories);
  };

  const handleCreateCategoryFormReset = (clearFilters) => {
    clearFilters({ confirm: true });
    state.searchText = '';
  };
</script>
